<template>
  <!-- rowData?.brId ? '修改档案' : '患者档案' -->
  <a-modal :open="open" width="1100px" centered @cancel="onCancel">
    <template #title>
      <div class="flex justify-between">
        <span class="w-16">{{ rowData?.brId ? '修改档案' : '患者档案' }}</span>
        <div v-if="isMedical" class="flex-1 pr-16 text-center -mt-2">
          <a-radio-group v-model:value="tabActiveKey" button-style="solid" size="large" @change="onTabRadioChange">
            <a-radio-button v-for="(item, index) in tabData" :key="index" :value="item.key">{{ item.name }}</a-radio-button>
          </a-radio-group>
        </div>
      </div>
    </template>
    <div v-if="!isArmy" class="w-full overflow-auto pr-2.5 h-[400px] 2xl:h-[600px]">
      <div v-if="tabActiveKey !== '0001'">
        <div class="flex justify-between items-center">
          <div class="flex items-center">
            <BaseTitle title="医保信息" class="!mb-0 !w-[100px]" />
            <a-input v-if="tabActiveKey === '01'" v-model:value="formState.ck" placeholder="请扫描电子凭证" class="w-[450px]" @keyup.enter="readYbSrzCard" />
          </div>
          <!-- v-if="tabActiveKey !== '04' && tabActiveKey !== '05'" -->
          <a-button type="primary" @click="readYbSrzCard">读卡</a-button>
        </div>
        <div class="flex justify-between items-center mt-4">
          <LabelValue label-class="" label="社保卡号" :width="240" tooltip :value="medFormState.insureNo" />
          <LabelValue label-class="" label="有效期" :width="190" tooltip :value="medFormState.paus_insu_date" />
          <LabelValue label-class="" label="识别码" :width="310" tooltip :value="medFormState.ksbm_new" />
        </div>
      </div>
      <a-divider v-if="tabActiveKey !== '0001'" class="my-4" />
      <PatientInfoFormDefend v-if="!isArmy" :key="componentsKey" v-model:value="formState" item-class="w-1/3" />
    </div>
    <template #footer>
      <a-button @click="onClickReset()">重置</a-button>
      <a-button type="primary" @click="onSave(1)">保存</a-button>
      <a-button v-if="isSave" type="primary" @click="onSave(2)">保存并挂号</a-button>
    </template>
    <RegisterModal v-model:open="editOpen" :row-data="{ ...formState }" title="挂号" @success="onSuccess" />
  </a-modal>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { post, get } from '@/utils/request'
import cofirmModal from '@/utils/confirm.js'
import { getSystemConfig } from '@/utils/systemConfig'
import RegisterModal from '@/components/RegisterModal'
import useUserStore from '@/store/user'

const { empId } = useUserStore()

const props = defineProps({
  open: Boolean,
  rowData: {
    type: Object,
    default: () => ({})
  },
  isSave: {
    type: Boolean,
    default: () => false
  }
})
const router = useRouter()
const emit = defineEmits(['update:open', 'success'])
const loading = ref(true)
const editOpen = ref(false)
const componentsKey = ref(Math.random())
const isRegister = ref()
const isCounselor = ref()
const isMedical = ref()
const formState = ref({})
const tabActiveKey = ref('0001')
const printJson = ref('') // json
// const MedicalInfo = ref('')
const jsonStr = ref('')
const tabData = ref([
  {
    key: '0001',
    name: '自费'
  },
  {
    key: '03',
    name: '社保卡'
  },
  {
    key: '02',
    name: '身份证'
  },
  {
    key: '01',
    name: '电子凭证'
  },
  {
    key: '04',
    name: '刷脸授权'
  },
  {
    key: '05',
    name: '终端扫码'
  }
])

// 医保切换
const onTabRadioChange = async (e) => {
  let businessType = 0
  if (e.target.value === '03' || e.target.value === '02') {
    businessType = 1
  } else if (e.target.value === '01' || e.target.value === '05') {
    businessType = 3
  } else if (e.target.value === '00') {
    businessType = 0
  } else if (e.target.value === '04') {
    businessType = '01201'
  }
  if (e.target.value !== '0001') {
    const res = await post('/outp/mzdj/getMedicareCardSettinglnfo', { businessType })
    if (res.code !== 0) return message.error(res.msg)
    printJson.value = res.data
  }
}

const medFormState = ref({})
// const isGb = ref(true) //false 五期 true 国平

//读取社保卡/身份证/电子凭证
const readYbSrzCard = async () => {
  if (tabActiveKey.value === '03') {
    jsonStr.value = window.openExe?.readYBK(printJson.value) //社保卡
  } else if (tabActiveKey.value === '02') {
    jsonStr.value = window.openExe?.readSFZ(printJson.value) //身份证
  } else if (tabActiveKey.value === '01') {
    jsonStr.value = window.openExe?.readDZPZ(formState.value.ck, printJson.value) //电子凭证
  } else if (tabActiveKey.value === '04' || tabActiveKey.value === '05') {
    const res = await post('/common/masterData/getByYsbhDepartment', { empId: empId })
    if (res.code !== 0) message.error(res.msg || '获取登录人科室失败')
    const params = JSON.parse(printJson.value)
    const paramsJson = JSON.stringify({ ...params, fficeid: res.data?.ksdm, officename: res.data?.ksmc, slurl: getSystemConfig('FACE_SWIPING_URL') })
    jsonStr.value = tabActiveKey.value === '04' ? window.openExe?.readSL(paramsJson) : window.openExe?.readSLSM(paramsJson) //刷脸
  }
  const res = await post('/outp/mzdj/getReadPatientInfo', {
    jsonStr: jsonStr.value,
    mdtrtCertNo: '',
    mdtrtCertType: tabActiveKey.value === '04' || tabActiveKey.value === '05' ? '01' : tabActiveKey.value
  })
  if (res.code !== 0) return message.error(res.msg || '读卡失败')
  if (!res.data.ybkResonse?.br_id) return message.error('无病人信息')
  const { code, data = {}, msg } = await get('/common/patient/getPatientInfo?br_id=' + res.data.ybkResonse?.br_id)
  if (code !== 0) return message.error(msg || '获取患者信息失败')
  formState.value = data || {}
  // isGb.value = res.data.isgb
  medFormState.value = { ...res.data.baseinfo, ck: formState.value.ck, insureNo: res.data.ybkResonse?.kh, ksbm_new: res.data.ybkResonse?.ksbm_new } || {}
  // medFormState.value.insureNo = res.data.ybkResonse?.kh
}

const onCancel = () => {
  componentsKey.value = Math.random()
  emit('update:open', false)
}
const onSuccess = () => {
  componentsKey.value = Math.random()
  emit('update:open', false)
  emit('success')
}
const onSave = async (state) => {
  // 验证：检查是否提供了必要的患者信息
  if (!formState.value.brName || !formState.value.pyjm || !formState.value.brAge || (isCounselor.value && !formState.value.brZxsName)) {
    return message.error('请填写患者信息')
  }
  if (formState.value.isBrBlkh && !formState.value.brBlkh) {
    return message.error('请填写病历号')
  }
  // 验证：如果类型为 '身份证'，检查是否提供了身份证，并对其进行验证
  const idCard = formState.value.brSfz
  if (formState.value.brZjlx === '身份证' && idCard && idCard.length) {
    const { code: codeZjh, msg: msgZjh } = await post('/common/util/getCsrq', { sfzhm: idCard })
    if (codeZjh !== 0) {
      return message.error(msgZjh || '身份证有误')
    }
  }
  // 根据条件设置 jksy 值
  if (formState.value.jksy !== 0) {
    formState.value.jksy = formState.value?.brId ? 2 : 1
  }
  // 按断年龄是否为0，
  if (formState.value.brAge === '0') {
    const isAgeConfirm = await cofirmModal({ title: '提示', content: '当前患者年龄为0,请确认是否真实?' })
    if (!isAgeConfirm) {
      return
    }
  }
  // 新增状态下判断手机号是否已经存在，如果data>0,就是已存在，提示手机号已存在，点确认可以继续保存
  if (formState.value?.brMob && !props.rowData?.brId) {
    const { code, data, msg } = await get('/common/patient/getPatientMob?brMob=' + formState.value.brMob)
    if (code !== 0) return message.error(msg)
    if (data > 0) {
      const isConfirm = await cofirmModal({ title: '提示', content: '手机号已存在' })
      if (isConfirm) {
        onSavePatientInfo(state)
      }
    } else {
      onSavePatientInfo(state)
    }
  } else {
    onSavePatientInfo(state)
  }
}

// 保存患者信息
const onSavePatientInfo = async (state) => {
  // 保存患者信息
  const res = await post('/common/patient/savePatientInfo', {
    ...formState.value,
    insureStatus: tabActiveKey.value !== '0001' ? 1 : undefined
  })
  if (res.code === 0) {
    onSuccess()
    // 根据条件打开编辑模式或跳转到注册页面
    if (state === 2) {
      formState.value.brId = res.data
      if (isRegister.value) {
        editOpen.value = true
      } else {
        router.push({
          path: '/out-registration/register',
          query: {
            id: formState.value.brId
          }
        })
      }
    }
  } else {
    if (props.rowData?.brId) {
      return message.error(res.msg)
    }
    // 弹出错误确认框；如果确认，修改 jksy 值重新保存
    const isConfirm = await cofirmModal({ title: '提示', content: res.msg })
    if (isConfirm) {
      formState.value.jksy = 0
      await onSave(state)
    }
  }
}

const onClickReset = () => {
  if (props.rowData?.brId) {
    formState.value = { ...props.rowData }
  } else {
    // 清空其他项，收费标准默认选中第一个
    formState.value = {}
  }
}
watch(
  () => props.open,
  async (val) => {
    if (val) {
      if (props.rowData?.brId) {
        getPatientInfo()
        getSystemList()
        // formState.value = { ...props.rowData }
      }
    } else {
      // 清空其他项，收费标准默认选中第一个
      formState.value = {}
      medFormState.value = {}
      tabActiveKey.value = '0001'
    }
  }
)

// 获取患者信息
const getPatientInfo = async () => {
  const { code, data = {} } = await get('/common/patient/getPatientInfo?br_id=' + props.rowData?.brId)
  if (code !== 0) return message.error('获取患者信息失败')
  formState.value = { ...formState.value, ...data, brAge: data.brAge?.toString() }
}

// 获取数据权限
const getSystemList = async () => {
  const { code, data } = await post('/operation/opex/getEmpSystemDataPermissionsList', { empId })
  if (code !== 0) return message.error('获取数据权限失败')
  const isCode = data.some((i) => i.permissonCode === 'system:patient:modify')
  !isCode && (formState.value.isCode = true)
}
const isArmy = getSystemConfig('NAVYHIS_MODE') === '1'
onMounted(() => {
  setTimeout(() => {
    loading.value = false
  }, 100)
  isRegister.value = getSystemConfig('GHDJYS') === '1' //挂号登记样式
  isCounselor.value = getSystemConfig('IS_REQUIRED_CONSULTANT') === '1' //是否咨询师必填
  isMedical.value = getSystemConfig('IS_EXIST_MEDICAL_INSURANCE') === '1' //是否启用医保
})
</script>
